import { useEffect, useState, useRef, useCallback } from 'react'
import { ImageUploader, Popup, Space, Image, Swiper, ImageViewer, Button, Toast, Modal } from 'antd-mobile'
import { useNavigate, useParams } from 'react-router-dom'
import { meetingImageList, addMeetingImages, meetingDel, delMeetingImages, meetingExport } from '@api'
import { uploadFileToOSS } from '@utils/upload'
import useFileDownloader from '@hooks/useFileDownloader'
import axios from 'axios'
import './index.scss'

const tab = ['详情', '图片列表']

const Meeting_details = () => {
    const navigate = useNavigate()
    const { meetingId } = useParams()

    const { downloadFile } = useFileDownloader()

    const imagesList = useRef()

    const [visible2, setVisible2] = useState(false)

    const [tabIndex, setTabIndex] = useState(0)

    const [images, setImages] = useState([])

    const [isSelect, setIsSelect] = useState(false)
    const [selectList, setSelectList] = useState([])

    const [list, setList] = useState([])

    const [visible, setVisible] = useState(false)

    const [fileList, setFileList] = useState([])

    const [details, setDetails] = useState({})

    const [level, setLevel] = useState(null)

    useEffect(() => {
        const obj = JSON.parse(localStorage.getItem('meetingItem') || '{}')
        setDetails(obj)
        const obj2 = JSON.parse(localStorage.getItem('userInfo') || '{}')
        setLevel(obj2.level)
    }, [])

    // 上传
    const upload = async (file) => {
        const { res } = await uploadFileToOSS({ file })
        try {
            console.log(res.requestUrls[0].split('?')[0])
            return { url: res.requestUrls[0].split('?')[0] }
        } catch (error) {
            throw new Error(error)
        }
    }

    // 图片列表
    const getImages = useCallback(() => {
        meetingImageList(meetingId).then(({ success, data, info }) => {
            if (success) {
                setImages(data)
            } else {
                Toast.show(info)
            }
        })
    }, [meetingId])

    useEffect(() => {
        tabIndex === 1 && getImages()
    }, [tabIndex, getImages])

    // 重置
    const reset = () => {
        setVisible(false)
        setFileList([])
    }

    // 多选/取消多选
    const selectChange = () => {
        setSelectList([])
        setIsSelect(!isSelect)
    }

    const selectFun = (imageObj) => {
        setSelectList((prevArr) => {
            const imageIndex = prevArr.findIndex((img) => img.id === imageObj.id)
            if (imageIndex !== -1) {
                return prevArr.filter((currentImage) => currentImage.id !== imageObj.id)
            } else {
                return [...prevArr, imageObj]
            }
        })
    }

    // 上传图片
    const uploadFun = () => {
        if (fileList?.length) {
            addMeetingImages({ images: fileList.map((e) => e.url), meetingId }).then(({ success, info }) => {
                Toast.show(info)
                if (success) {
                    getImages()
                    reset()
                }
            })
        } else {
            Toast.show('请先选择图片')
        }
    }

    const del = () => {
        Modal.confirm({
            title: '确认操作',
            content: '您确定要删除此记录吗？',
            confirmText: '确认',
            cancelText: '取消',
            onConfirm: () => {
                meetingDel(details.id).then(({ success, info }) => {
                    if (success) {
                        Toast.show('删除成功~')
                        navigate(-1)
                    } else {
                        Toast.show(info)
                    }
                })
            }
        })
    }

    // 批量下载
    const batchDownload = async () => {
        console.log(selectList)
        if (selectList?.length) {
            for (const { image } of selectList) {
                try {
                    const response = await axios.get(image, {
                        responseType: 'blob' // 设置响应类型为 blob，以便处理二进制文件
                    })

                    // 创建一个临时链接元素，设置 href 为 blob URL，并模拟点击以启动下载
                    const link = document.createElement('a')
                    link.href = window.URL.createObjectURL(new Blob([response.data]))
                    link.setAttribute('download', image.split('/').pop()) // 设置下载文件名为 URL 的最后一部分
                    document.body.appendChild(link)
                    link.click()
                    link.parentNode.removeChild(link) // 下载后从 DOM 中移除该元素
                } catch (error) {
                    console.error('下载图片失败:', error)
                }
            }
        } else {
            Toast.show('请先选择图片')
        }
    }

    // 删除图片
    const delImage = () => {
        if (selectList.length) {
            Modal.confirm({
                title: '确认操作',
                content: '您确定要批量删除图片吗？',
                confirmText: '确认',
                cancelText: '取消',
                onConfirm: () => {
                    const ids = selectList.map((e) => e.id)
                    delMeetingImages(ids).then(({ success, info }) => {
                        Toast.show(info)
                        if (success) {
                            setIsSelect(false)
                            setSelectList([])
                            getImages()
                        }
                    })
                }
            })
        } else {
            Toast.show('至少选择一张图片~')
        }
    }

    const exportMeeting = () => {
        Toast.show({
            content: '正在导出~',
            icon: 'loading',
            duration: 0,
            maskClickable: false
        })

        try {
            meetingExport({ id: meetingId }).then(({ success, data, info }) => {
                Toast.clear()
                if (success && data) {
                    downloadFile(data)
                } else {
                    Toast.show({
                        icon: 'fail',
                        content: info
                    })
                }
            })
        } catch (err) {
            console.error('Error fetching file URL:', err)
        }
    }

    const handleFileChange = async (e) => {
        const files = Array.from(e.target.files);
        // 限制只能上传一个文件
        if (files.length > 1) {
            Toast.show('只能上传一个文件！');
            return;
        }
        console.log(files)
        Toast.show({
            content: '正在上传~',
            icon: 'loading',
            duration: 0,
            maskClickable: false
        })
        const { res } = await uploadFileToOSS({ file: files[0] })
        try {
            console.log(res.requestUrls[0].split('?')[0])
            Toast.clear()
            addMeetingImages({ images: [res.requestUrls[0].split('?')[0]], meetingId }).then(({ success, info }) => {
                Toast.show(info)
                if (success) {
                    getImages()
                    reset()
                }
            })
        } catch (error) {
            Toast.clear()
            throw new Error(error)
        }
    };

    const Render = ({ item, callback }) => {
        let fileType = ''
        const extension = item.split('.').pop().toLowerCase();
        if (['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(extension)) {
            fileType = 'image';
        } else if (['mp4', 'avi', 'mkv', 'mov'].includes(extension)) {
            fileType = 'video';
        } else {
            fileType = 'file';
        }
        switch (fileType) {
            case 'image':
                return <Image onClick={callback}
                    width={110}
                    fit="cover" src={item} />;
            case 'video':
                return (
                    <video controls width={110} height={150} style={{ objectFit: 'fill' }} poster={`${item}?x-oss-process=video/snapshot,t_0,f_jpg,w_160,h_120,m_fast`}>
                        <source src={item} type="video/mp4" />
                        Your browser does not support the video tag.
                    </video>
                );
            case 'file':
                return (
                    <div style={{ width: '110px', height: '150px',wordWrap: 'break-word' }}>
                        <p>{item.split('/').pop()}</p>
                        <a href={item} download>
                            下载文件
                        </a>
                    </div>
                );
            default:
                return null;
        }
    }

    return (
        <div className="Meeting_details">
            <div className="Meeting_details_tab_box">
                <div>
                    {tab.map((e, i) => (
                        <p className={tabIndex === i ? 'active' : ''} key={i} onClick={() => setTabIndex(i)}>
                            {e}
                        </p>
                    ))}
                    <span className={tabIndex ? 'active' : ''}></span>
                </div>
                {tabIndex ? (
                    <div>
                        <Button color="primary" size="mini" onClick={selectChange}>
                            {isSelect ? '取消' : ''}多选
                        </Button>
                        <Button color="primary" size="mini" onClick={batchDownload}>
                            批量下载
                        </Button>
                        {level !== 3 ? (
                            <Button color="danger" size="mini" onClick={delImage}>
                                批量删除
                            </Button>
                        ) : null}
                    </div>
                ) : null}
            </div>
            {!tabIndex ? (
                <>
                    {details.imagesList ? (
                        <Swiper>
                            {details.imagesList.map((item, index) => (
                                <Swiper.Item key={item}>
                                    <Image
                                        height={250}
                                        fit="cover"
                                        src={item}
                                        onClick={() => {
                                            imagesList?.current.swipeTo(index)
                                            setList(details.imagesList)
                                            setVisible2(true)
                                        }}
                                    />
                                </Swiper.Item>
                            ))}
                        </Swiper>
                    ) : null}

                    <div className="Meeting_details_info">
                        {level !== 3 ? (
                            <Button onClick={() => navigate(`/meeting/add/${details.id}`)} style={{ margin: '10px 0' }} color="primary" size="mini">
                                编辑
                            </Button>
                        ) : null}
                        <Button onClick={exportMeeting} style={{ marginLeft: '10px' }} color="primary" size="mini">
                            导出
                        </Button>
                        {level === 0 || level === 1 ? (
                            <Button onClick={del} style={{ marginLeft: '10px' }} color="danger" size="mini">
                                删除
                            </Button>
                        ) : null}
                        <h2>
                            {details.title}
                            <span>（{details.type}）</span>
                        </h2>
                        <h5>{details.content}</h5>
                        <p>
                            时间：<span>{details.time}</span>
                        </p>
                        <p>
                            记录人员：<span>{details.person}</span>
                        </p>
                        <p>
                            地址：<span>{details.address}</span>
                        </p>
                    </div>
                </>
            ) : (
                <div className="Meeting_details_images">
                    {images.map((item, index) => (
                        <div key={index}>
                            <div className="Meeting_details_images_head">
                                <p>{item.uploadTime}</p>
                            </div>
                            <Space wrap justify="start">
                                {item.images.map((ee, ii) => (
                                    <div className="Meeting_details_images_box" key={ee.id}>
                                        {isSelect ? (
                                            <div className="Meeting_details_images_mask" onClick={() => selectFun(ee)}>
                                                <span className={selectList.some((img) => img.id === ee.id) ? 'active' : ''}></span>
                                            </div>
                                        ) : null}
                                        <Render
                                            item={ee.image}
                                            callback={() => {
                                                imagesList?.current.swipeTo(ii)
                                                setList(item.images.map((e) => e.image))
                                                setVisible2(true)
                                            }} />
                                        {/* {Render(ee.image,)} */}
                                        {/* <Image
                                            onClick={() => {
                                                imagesList?.current.swipeTo(ii)
                                                setList(item.images.map((e) => e.image))
                                                setVisible2(true)
                                            }}
                                            width={110}
                                            fit="cover"
                                            src={ee.image}
                                        /> */}
                                    </div>
                                ))}
                            </Space>
                        </div>
                    ))}
                    <div className="Meeting_details_btn">
                        <Button block type="submit" color="primary" size="large" onClick={() => setVisible(true)}>
                            添加图片
                        </Button>
                        {/* <Button block type="submit" color="primary" size="large" type="file">
                            添加文件
                        </Button> */}
                        <input
                            type="file"
                            accept="*/*"  // 允许所有文件类型
                            multiple
                            style={{ display: 'none' }}
                            onChange={handleFileChange}
                            id="file-upload-input"
                        />
                        <Button onClick={() => document.getElementById('file-upload-input').click()}>
                            点击上传文件
                        </Button>
                    </div>
                </div>
            )}

            <Popup visible={visible} onMaskClick={reset} onClose={reset} bodyStyle={{ height: '60vh' }}>
                <div className="upload_images">
                    <ImageUploader
                        style={{ '--cell-size': '110px' }}
                        value={fileList}
                        multiple
                        upload={upload}
                        maxCount={9}
                        showUpload={fileList.length < 9}
                        onChange={setFileList}
                        onCountExceed={(exceed) => {
                            Toast.show(`最多选择 ${9} 张图片，你多选了 ${exceed} 张`)
                        }}
                    />
                    <Button color="primary" onClick={uploadFun}>
                        上传图片
                    </Button>
                </div>
            </Popup>

            <ImageViewer.Multi
                ref={imagesList}
                images={list}
                visible={visible2}
                defaultIndex={1}
                onClose={() => {
                    setVisible2(false)
                }}
            />
        </div>
    )
}
export default Meeting_details
